// 使用代理路径调用Kimi API，避免跨域问题
const KIMI_API_KEY = "sk-Sc2EtPSGBDYC7aOW3WINdiA5y8FB0cBot9z1wMut3CgSErLw";
const KIMI_BASE_URL = "/kimi-api";

// 检查 API Key 是否有效
if (!KIMI_API_KEY || KIMI_API_KEY.length < 10) {
  console.error('API Key 无效或未配置');
}

// 文件类型定义
export interface FileItem {
  file: File;
  preview?: string;
  id: string;
}

// 构建多模态消息内容
const buildMultimodalContent = (text: string, files: FileItem[]): any[] => {
  const content: any[] = [];

  // 添加文本内容
  if (text.trim()) {
    content.push({
      type: "text",
      text: text
    });
  }

  // 添加文件内容
  files.forEach(fileItem => {
    if (fileItem.file.type.startsWith('image/')) {
      // 图片文件
      content.push({
        type: "image_url",
        image_url: {
          url: fileItem.preview || ""
        }
      });
    } else if (fileItem.file.type === 'application/pdf') {
      // PDF文件 - 需要转换为base64
      content.push({
        type: "image_url",
        image_url: {
          url: `data:application/pdf;base64,${fileItem.preview || ""}`
        }
      });
    }
  });

  return content;
};

// 发送消息到Kimi AI（支持多模态）
export const sendMessageToAI = async (message: string, files: FileItem[] = []): Promise<string> => {
  try {
    const content = buildMultimodalContent(message, files);

    console.log('发送请求到:', `${KIMI_BASE_URL}/chat/completions`);

    const response = await fetch(`${KIMI_BASE_URL}/chat/completions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${KIMI_API_KEY}`,
      },
      body: JSON.stringify({
        model: "moonshot-v1-8k",
        messages: [
          {
            role: "system",
            content: "你是一个专业的健康咨询助手，请用专业、友好的语气回答用户的健康相关问题。你可以分析用户上传的图片和文件，提供专业的健康建议。"
          },
          {
            role: "user",
            content: content
          }
        ],
        temperature: 0.7,
        max_tokens: 2000,
      }),
    });

    console.log('API响应状态:', response.status);
    console.log('API响应头:', Object.fromEntries(response.headers.entries()));

    if (!response.ok) {
      const errorText = await response.text();
      console.error('API错误详情:', errorText);
      throw new Error(`API请求失败: ${response.status} - ${errorText}`);
    }

    const data = await response.json();
    console.log('API响应数据:', data);
    return data.choices[0]?.message?.content || '抱歉，我无法回答您的问题。';
  } catch (error) {
    console.error('Kimi API调用失败:', error);
    console.error('错误类型:', error.constructor.name);
    console.error('错误消息:', error.message);
    throw new Error(`AI服务暂时不可用: ${error.message}`);
  }
};

// 发送带上下文的对话（支持多模态）
export const sendMessageWithContext = async (
  messages: Array<{ role: string, content: string | any[] }>,
  files: FileItem[] = []
): Promise<string> => {
  try {
    // 处理最后一条用户消息，添加文件内容
    const processedMessages = [...messages];
    if (processedMessages.length > 0 && processedMessages[processedMessages.length - 1].role === 'user') {
      const lastMessage = processedMessages[processedMessages.length - 1];
      if (typeof lastMessage.content === 'string') {
        const content = buildMultimodalContent(lastMessage.content, files);
        processedMessages[processedMessages.length - 1] = {
          ...lastMessage,
          content: content
        };
      }
    }

    console.log('发送上下文请求到:', `${KIMI_BASE_URL}/chat/completions`);

    const response = await fetch(`${KIMI_BASE_URL}/chat/completions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${KIMI_API_KEY}`,
      },
      body: JSON.stringify({
        model: "moonshot-v1-8k",
        messages: [
          {
            role: "system",
            content: "你是一个专业的健康咨询助手，请用专业、友好的语气回答用户的健康相关问题。你可以分析用户上传的图片和文件，提供专业的健康建议。"
          },
          ...processedMessages
        ],
        temperature: 0.7,
        max_tokens: 2000,
      }),
    });

    console.log('上下文API响应状态:', response.status);
    console.log('上下文API响应头:', Object.fromEntries(response.headers.entries()));

    if (!response.ok) {
      const errorText = await response.text();
      console.error('上下文API错误详情:', errorText);
      throw new Error(`API请求失败: ${response.status} - ${errorText}`);
    }

    const data = await response.json();
    console.log('上下文API响应数据:', data);
    return data.choices[0]?.message?.content || '抱歉，我无法回答您的问题。';
  } catch (error) {
    console.error('Kimi API调用失败:', error);
    console.error('错误类型:', error.constructor.name);
    console.error('错误消息:', error.message);
    throw new Error(`AI服务暂时不可用: ${error.message}`);
  }
};